package cn.com.huzo.webapp.controller.master;

import cn.com.huzo.model.entities.master.SupplierCatalogueEntity;
import huzofw.common.web.controller.BaseFormController;
import cn.com.huzo.model.entities.master.SupplierEntity;
import cn.com.huzo.service.master.SupplierCatalogueManager;
import cn.com.huzo.service.master.SupplierManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 供应商信息控制器
 *
 * @author 吴旭
 */
@Controller
public class SupplierController extends BaseFormController {

    // <editor-fold defaultstate="collapsed" desc="属性">
    @Resource(name = "SupplierManager")
    private SupplierManager _manager;

    @Resource(name = "SupplierCatalogueManager")
    private SupplierCatalogueManager _managerCatalogue;
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="画面处理部分">
    /**
     * 跳转到供应商一览画面
     * <p>
     * @return
     */
    @RequestMapping("master/supplier/list.html")
    public ModelAndView redirectListWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("master.supplier.list.def");
        return view;
    }

    /**
     * 供应商编辑画面
     * <p>
     * @param action 操作类别 1：增加 2：编辑
     * @param supplierId 供应商标识
     * @param nodeId 所属目录标识
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("master/supplier/{action}/{supplierId}/{nodeId}/edit.html")
    public ModelAndView redirectEditWnd(@PathVariable(value = "action") int action,
            @PathVariable(value = "supplierId") Long supplierId,
            @PathVariable(value = "nodeId") Long nodeId) throws Exception {
        ModelAndView view = new ModelAndView();
        // 为画面设置变量
        view.addObject("action", action);
        view.addObject("supplierId", supplierId);

        if (nodeId != 0L) {
            SupplierCatalogueEntity _item = _managerCatalogue.fetchByKey(nodeId);
            view.addObject("nodeId", nodeId);
            view.addObject("nodeText", _item.getParentName() + " → " + _item.getCatalogueName());
        }

        view.setViewName("master.supplier.edit.def");
        return view;
    }

    /**
     * 弹出供应商选择画面
     * <p>
     * @return
     */
    @RequestMapping("master/supplier/choice.html")
    public ModelAndView redirectChoiceWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.master.supplier.choice.def");
        return view;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="数据处理部分">
    /**
     * 根据标识取得供应商数据。
     *
     * @param criterion 供应商标识、当前用户、流程标识
     * @return 供应商数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/supplier/fetchByKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    SupplierEntity fetchByKey(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.fetchByKey(MapUtils.getLong(criterion, "HeaderId"));
    }

    /**
     * 根据供应商编码取得供应商数据。
     *
     * @param criterion 供应商编码
     * @return 供应商数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/supplier/fetchByNo.html",
            method = RequestMethod.POST)
    public @ResponseBody
    SupplierEntity fetchByNo(@RequestBody final Map<String, Object> criterion) throws Exception {
        String supplierNo = (String) criterion.get("SupplierNo");
        SupplierEntity _temp = _manager.fetchBySupplierNo(supplierNo);
        if (_temp == null) {
            _temp = new SupplierEntity();
        }
        return _temp;
    }

    /**
     * 删除。
     *
     * @param criterion 要删除的数据
     * @return 返回删除后的数据
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/supplier/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> delete(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.delete(criterion);
    }

    /**
     * 根据条件取得供应商信息分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 供应商信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "master/supplier/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchForPage(@RequestBody Map<String, Object> criterion) throws Exception {
        return _manager.fetchForPage(criterion);
    }

    /**
     * 保存供应商信息数据。
     * <p>
     * @param instance 要保存的供应商信息对象。
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "master/supplier/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Long save(@RequestBody SupplierEntity instance) throws Exception {
        Long rowsAffected;

        if (instance.getSupplierId() > 0) { //编辑
            rowsAffected = (long) _manager.update(instance);
        } else {//新增
            rowsAffected = _manager.insert(instance);
        }

        return rowsAffected;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="导出数据处理部分">
    /**
     * 弹出导出excel输出列选择画面
     * <p>
     * @return
     */
    @RequestMapping("popup/master/supplier/exportPopupWnd.html")
    public ModelAndView redirectExportExcelWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popupWnd/80_master/supplierExportExcelPopupWnd");
        return view;
    }

    /**
     * 得到全部供应商表的字段列表
     *
     * @return 全部字段列表
     * @throws java.lang.Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "master/supplier/fetchAllFields.html",
            method = RequestMethod.POST,
            produces = {"application/xml", "application/json"})
    public @ResponseBody
    List<SupplierEntity> fetchAllFields() throws Exception {
        return _manager.fetchAllFields();
    }

    /**
     * 导出供应商表到excel
     *
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "master/supplier/export.html",
            method = RequestMethod.POST)
    public ModelAndView exportViewExcelMaterial(HttpServletRequest request) throws Exception {
        Long Id = Long.parseLong(request.getParameter("_SupplierTypeId").trim());
        String suppliertype = request.getParameter("_SupplierType").trim();
        //    JSONObject fieldslist = JSONObject.fromObject(request.getParameter("_FieldsList")); 
        String fieldslist = request.getParameter("_FieldsList");
        String commentlist = request.getParameter("_CommentList");
        String suppliername = request.getParameter("_SupplierName");
        String suppliercode = request.getParameter("_SupplierCode");

        Map<String, Object> criterion = new HashMap();
        criterion.put("SupplierTypeId", Id);
        criterion.put("SupplierName", suppliername);
        criterion.put("SupplierCode", suppliercode);

        //     criterion.put("FieldsList", fieldslist); 
        String[] fieldsArr = fieldslist.split(",");
        List<String> lineslist = new ArrayList<>();
        //循环    
        for (Integer i = 0; i < fieldsArr.length; i++) {
            criterion.put("FieldName", fieldsArr[i]);
            List<String> linesdata = _manager.fetchExportData(criterion);
            //把list变成字符串
            String str = "";
            for (Integer j = 0; j < linesdata.size(); j++) {
                if (j == linesdata.size() - 1) {
                    str += linesdata.get(j);
                } else {
                    str += linesdata.get(j) + ",";
                }
            }
            lineslist.add(str);
        }
        //     List<MaterialEntity> lineslist= _manager.fetchAllByMaterialTypeId(criterion);
        Map<String, Object> model = new HashMap();
        model.put("lineslist", lineslist);
        model.put("suppliertype", suppliertype);
        model.put("commentlist", commentlist);
        return new ModelAndView("SupplierExcelView", model);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="批量更新处理部分">
    /**
     * 批量更新供应商所属目录。
     *
     * @param itemList 要处理的数据列表
     * @return
     *
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/supplier/changeCatalogue.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Integer batchChangeCatalogue(@RequestBody final Map<String, ? extends List<SupplierEntity>> itemList) throws Exception {
        int rowsAffected = 0;
        if (itemList.get("updateList").size() > 0) {
            rowsAffected = _manager.batchChangeCatalogue(itemList.get("updateList"));
        }

        return rowsAffected;
    }
    // </editor-fold>
}
